import requests
import re
import time
import datetime

def get_first_parts_from_A_arrays_v2_optimized(today_date):
    """
    优化版本：获取所有A数组中指定位置的内容
    
    Returns:
        list: 包含解析后数据的列表，每个元素为包含[first_part, fifth_sixth_part, eighth_ninth_part]的列表
    """
    # 生成URL
    timestamp = int(time.time() * 1000)
    r = "007" + str(timestamp)
    url = f'https://livestatic.titan007.com/vbsxml/bfdata_ut.js?r={r}'
    
    # 请求头
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.5845.97 Safari/537.36 Core/1.116.541.400 QQBrowser/19.4.6579.400',
        'Referer': 'https://vip.titan007.com/'
    }
    
    # 发送请求，设置超时时间
    response = requests.get(url, headers=headers, timeout=10)
    # 直接使用UTF-8编码，避免检测编码的开销（根据网站实际情况调整）
    response.encoding = 'utf-8'
    content = response.text
    
    # 使用编译的正则表达式提高匹配效率
    pattern = re.compile(r'A\[\d+\][^"]*"([^"]*)"')
    matches = pattern.findall(content)
    
    today_date = datetime.datetime.strptime(today_date, "%Y%m%d").strftime("%Y-%m-%d")

    # 预分配结果列表大小（如果可以预估）
    result_parts = []
    
    # 优化的解析逻辑
    for string_content in matches:
        # 按^分割内容，但只分割到我们需要的索引位置，避免完全分割
        parts = string_content.split('^')

        # 理第13部分，获取赛事是否开始比赛 0 = 未开始, 1, 2, 3... = 开始
        game_status_part = parts[13] if len(parts) > 13 else ""

        if game_status_part == "0" or game_status_part == "-14":
            # print("跳过比赛")
            continue
        
        # 获取所需部分，确保索引存在
        pid = parts[0] if len(parts) > 0 else ""

        # 理第二部分，获取赛事event_part
        league = parts[2] if len(parts) > 2 else ""

        # 处理第五部分，去除HTML标签
        fifth_sixth_part = parts[5] if len(parts) > 5 else ""
        # 去除HTML标签，例如将"墨西哥U20<font color=#880000>(中)</font>"处理为"墨西哥U20"
        if fifth_sixth_part:
            fifth_sixth_part = re.sub(r'<[^>]+>', '', fifth_sixth_part).strip()
        # 处理第八部分，去除HTML标签
        eighth_ninth_part = parts[8] if len(parts) > 8 else ""
        if eighth_ninth_part:
            eighth_ninth_part = re.sub(r'<[^>]+>', '', eighth_ninth_part).strip()

        listerPart = {
            "league": league,
            "home_team": fifth_sixth_part,
            "away_team": eighth_ninth_part,
            "pid": pid,
            "pidtime": today_date
        }

        result_parts.append(listerPart)
    
    return result_parts

# 使用示例
if __name__ == "__main__":
    print("开始提取数据...")
    import datetime
    today_date = '20251012'

    # 测试优化版本
    start_time = time.time()
    result_list_optimized = get_first_parts_from_A_arrays_v2_optimized(today_date)
    end_time = time.time()
    execution_time_optimized = end_time - start_time
    
    print("优化版本结果:")
    print("[", end="")
    for item in result_list_optimized:
        print(item)
    # 写入json文件
    # import json
    # with open('output.json', 'w', encoding='utf-8') as f:
    #     json.dump(result_list_optimized, f, ensure_ascii=False, indent=4)


    print(f"优化版本运行时间: {execution_time_optimized:.4f} 秒")
    print(f"优化版本结果数量: {len(result_list_optimized)}")